package system

import (
	"errors"
	"reflect"

	"github.com/go-playground/validator/v10"
)

type ValidatorService struct{}

// 自定义校验规则
func (v *ValidatorService) Validate(s interface{}) (err error) {
	validate := validator.New()
	err = validate.Struct(s)
	if err != nil {
		for _, validationErr := range err.(validator.ValidationErrors) {
			fieldName := validationErr.Field()
			tagName := validationErr.Tag()

			field, ok := reflect.TypeOf(s).FieldByName(fieldName)

			if ok {
				messageName := tagName + "_message"
				message := field.Tag.Get(messageName)

				if message != "" {
					return errors.New(message)
				}
				err = validationErr
			}
		}
	}
	return err
}
